let search_field = ""
let covers = [];
let video_obj = null;
const lblSearchTitle = document.getElementById('lblSearchTitle');
const addImageModal = document.getElementById('addImageModal');
const gridContainer = document.getElementById('gridContainer');
const CoversContainer = document.getElementById('CoversContainer');
const hiddenCoversField = document.getElementById('covers');
const btnSearchImage = document.getElementById('btnSearchImage');
const btnAddObject = document.getElementById('btnAddObject');
const hiddenVideoLlibraryField = document.getElementById('video_library');
const VideoContainer = document.getElementById('VideoContainer');


function showAddModal(to_field) {
    search_field = to_field;


    if (search_field === "covers") {
        lblSearchTitle.innerHTML = "选择图片";
        btnSearchImage.addEventListener('click', searchImage);
        btnAddObject.addEventListener('click', addImage);
    } else {
        lblSearchTitle.innerHTML = "选择视频";
        btnSearchImage.addEventListener('click', searchVideo);
        btnAddObject.addEventListener('click', addVideo);
    }

    addImageModal.classList.remove('hidden');
    addImageModal.classList.add('flex');
}

function hideAddModal() {
    search_field = "";
    search_image_key.value = "";
    video_obj = null;
    lblSearchTitle.innerHTML = "";
    gridContainer.innerHTML = "";
    btnSearchImage.removeEventListener('click', searchImage);
    btnSearchImage.removeEventListener('click', searchVideo);
    btnAddObject.removeEventListener('click', addImage);
    btnAddObject.removeEventListener('click', addVideo);
    addImageModal.classList.remove('flex');
    addImageModal.classList.add('hidden');
}

function toggleCheckbox(checkbox) {
    const icon = checkbox.querySelector('i');
    checkbox.classList.toggle('checked');
    icon.classList.toggle('hidden');
}


function searchImage() {
    gridContainer.innerHTML = "";
    axios.get("/image_library/list/" + search_image_key.value, {}, {
        headers: {
            'X-CSRFToken': document.getElementById('csrf_token').value, 'Content-Type': 'application/json'
        }
    }).then(response => {
        console.log(response.data.data.length)
        if (response.data.data.length !== 0) {
            gridContainer.classList.add('grid');
            response.data.data.forEach(img => {
                addSearchImage(gridContainer, img);
            });
        } else {
            gridContainer.classList.remove('grid');
            gridContainer.innerHTML = "暂无数据";
        }

    })
}

function addSearchImage(gridContainer, imageJson) {
    const check_data = JSON.stringify({id: imageJson.id, title: imageJson.title, file_url: imageJson.file_url})
    const tagElement = document.createElement('div');
    tagElement.className = 'image-container';
    tagElement.innerHTML = `<div class="checkbox-wrapper">
                                <div class="custom-checkbox " onclick="toggleCheckbox(this)" image_data='${check_data}'>
                                    <i class="fas fa-check hidden"></i></div></div>`;
    tagElement.innerHTML += `<div class="image-wrapper"><img src="${imageJson.file_url}" alt="${imageJson.title}"></div>`;
    gridContainer.appendChild(tagElement);
}


function addImage() {
    var elements = document.querySelectorAll('.custom-checkbox.checked');
    elements.forEach(function (element) {
        var imageJson = JSON.parse(element.getAttribute('image_data'));
        covers.push(imageJson);
    });

    updateCoversDisplay();
    updateHiddenCoverField();
    hideAddModal();
}


function updateHiddenCoverField() {
    console.log(JSON.stringify(covers));
    hiddenCoversField.value = JSON.stringify(covers);
}


function updateCoversDisplay(is_close = true) {
    CoversContainer.innerHTML = '';
    covers.forEach(cover => {
        const tagElement = document.createElement('div');
        tagElement.className = 'relative';
        tagElement.innerHTML = `<img src="${cover.file_url}" class="max-w-270 max-h-270 object-cover" alt="${cover.title}" />`;
        if (is_close) {
            tagElement.innerHTML += `<button type="button" class="btn-close absolute end-0 top-0 bg-white" onclick="removeCover(${cover.id})"></button>`;
        }

        CoversContainer.appendChild(tagElement);
    });
}

function removeCover(coverToRemove) {
    covers = covers.filter(cover => cover.id !== coverToRemove);
    updateCoversDisplay();
    updateHiddenCoverField();
}

function searchVideo() {
    gridContainer.innerHTML = "";
    axios.get("/video_library/list/" + search_image_key.value, {}, {
        headers: {
            'X-CSRFToken': document.getElementById('csrf_token').value, 'Content-Type': 'application/json'
        }
    }).then(response => {
        console.log(response.data.data.length)
        if (response.data.data.length !== 0) {
            gridContainer.classList.add('grid');
            response.data.data.forEach(video => {
                addSearchVideo(gridContainer, video);
            });
        } else {
            gridContainer.classList.remove('grid');
            gridContainer.innerHTML = "暂无数据";
        }
    })
}

function addSearchVideo(gridContainer, videoJson) {
    const check_data = JSON.stringify({id: videoJson.id, title: videoJson.title, file_url: videoJson.file_url})
    const tagElement = document.createElement('div');
    tagElement.className = 'image-container';
    tagElement.innerHTML = `<div class="radio-container">
                                <div class="custom-radio " onclick="radioSelectImage(this)" video_data='${check_data}'>
                                <i class="fas fa-check hidden"></i></div></div>`;
    tagElement.innerHTML += `<div class="image-wrapper"><video src="${videoJson.file_url}" class="h-full" controls controlslist="nodownload noremoteplayback nofullscreen" oncontextmenu="return false" disablePictureInPicture>您的浏览器不支持视频播放。</video>`;
    gridContainer.appendChild(tagElement);
}

function radioSelectImage(radio_box) {
    video_obj = JSON.parse(radio_box.getAttribute('video_data'));

    // 更新所有单选按钮状态
    document.querySelectorAll('.custom-radio').forEach(radio => {
        var imageJson = JSON.parse(radio.getAttribute('video_data'));
        radio.classList.toggle('checked', video_obj.id === imageJson.id);
    });
}

function addVideo() {
    updateVideoDisplay();
    updateHiddenVideoLlibraryIdField();
    hideAddModal();
}

function updateVideoDisplay(is_close = true) {
    VideoContainer.innerHTML = '';
    if (video_obj !== null && video_obj !== "") {
        const tagElement = document.createElement('div');
        tagElement.className = 'relative';
        tagElement.innerHTML = `<video src="${video_obj.file_url}" class="video_thumbnail rounded-lg" controls controlslist="nodownload noremoteplayback nofullscreen" oncontextmenu="return false" disablePictureInPicture>您的浏览器不支持视频播放。</video>`;
        if (is_close) {
            tagElement.innerHTML += `<button type="button" class="btn-close absolute end-0 top-0 bg-white" onclick="clearContainer()"></button>`;
        }
        VideoContainer.appendChild(tagElement);
    }
}


function updateHiddenVideoLlibraryIdField() {
    hiddenVideoLlibraryField.value = JSON.stringify(video_obj);
}

function clearContainer() {
    VideoContainer.innerHTML = '';
    hiddenVideoLlibraryField.value = '';
}


function initContainer() {
    if (hiddenCoversField.value !== JSON.stringify(covers)) {
        covers = JSON.parse(hiddenCoversField.value);
    }
    updateCoversDisplay();

    if (hiddenVideoLlibraryField.value.length > 0) {
        video_obj = JSON.parse(hiddenVideoLlibraryField.value);
    }
    updateVideoDisplay();
    video_obj = null;
}
